<template>
  <el-dialog title="生成报价单" :visible.sync="show" @close="cancel" width="80%" append-to-body>
    <el-form ref="form" :model="form" :rules="rules" label-width="90px">

      <el-row>
        <el-col :span="12">
          <el-form-item label="报价类型" prop="bjlx">
            <el-radio-group v-model="form.bjlx">
              <el-radio v-for="item in bjlxList" :label="item.dictValue">{{item.dictLabel}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="报价日期" prop="bjrq">
            <el-date-picker clearable
                            style="width: 100%"
                            v-model="form.bjrq"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择报价时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="导入类型" prop="drlx">
            <el-checkbox-group v-model="drlx" @change="selectDrlx">
              <el-checkbox v-for="item in drlxList" :label="item.dictValue">{{item.dictLabel}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="报价附件" prop="bjfj">
            <el-upload
              class="upload-demo"
              :action="src"
              name="files"
              :on-success="handleSuccess"
              :on-error="handleError"
              :before-remove="handleRemove"
              :headers="uploadHeaders"
              accept=".xlsx, .xls"
              :limit="1"
              :file-list="fjList"
              :on-preview="handlePreview"
            >
                <span slot="trigger">
                  <el-button size="small" type="primary"> <i class="el-icon-upload"></i> 点击上传</el-button>
                </span>
              <span style="margin-left: 10px" v-if="fjList.length > 0">
<!--                  <el-button size="small" :loading="genButton" type="primary" @click="genBjd">点击生成报价单</el-button>-->
                </span>
              <div slot="tip" class="el-upload__tip">
                只能上传Excel文件
              </div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getToken } from '@/utils/auth'
import { delFj, getFjById } from '@/api/gd/fj'
import axios from 'axios'

export default {
  name: 'zzbjd',
  props: {
    show: {
      type: Boolean,
      default: false
    },
    formInfo: {
      type: Object
    }
  },
  data() {
    return {
      drlx: [],
      buttonLoading: false,
      form: {},
      // 表单校验
      rules: {
        zbbh: [
          { required: true, message: "总部编号不能为空", trigger: "blur" }
        ],
        kh: [
          { required: true, message: "客户不能为空", trigger: "change" }
        ],
        dz: [
          { required: true, message: "地址不能为空", trigger: "change" }
        ],
        sfyxc: [
          { required: true, message: "是否已下场不能为空", trigger: "blur" }
        ],
        sfhk: [
          { required: true, message: "是否回款不能为空", trigger: "blur" }
        ]
      },
      // =========== 附件上传 =========
      src: this.uploadSrc + '/gd/fj/file/batchUpload',
      uploadHeaders: { 'Authorization': 'Bearer ' + getToken() }, // 如果需要CSRF保护的话
      fjList: [],
      // ========== 附件结束 =========
    }
  },
  created() {
    this.form = this.formInfo
    this.getDict()
  },
  methods: {
    submitForm() {
      console.log("this.form", this.form)
    },
    selectDrlx(val) {
      this.form.drlx = val.toString()
    },
    getDict() {
      // 报价类型
      this.getDicts("gd_bjlx").then(res => {
        this.bjlxList = res.data
      })
      // 导入类型
      this.getDicts("gd_drlx").then(res => {
        this.drlxList = res.data
      })
    },
    cancel() {
      this.$emit("close")
    },
    // ======  上传开始  ======
    handleSuccess(response, file, fileList) {
      if (response !== null && response !== undefined) {
        // 获取当前的上传的附件id
        let fileIds = []
        fileList.forEach(item => {
          if (item.response !== undefined) {
            fileIds.push(item.response[0].fj)
          }
        })
        this.fjList = fileList
        // 更新状态或者通知用户上传成功
        this.$message.success('上传成功');
        // 上传成功以后，将id设置
        this.form.bjfj = fileIds.toString()
      }
    },
    // 上传失败回调
    handleError(err, file) {
      // 处理错误并通知用户
      this.$message.error('上传失败：', err);
      this.fjList = []
    },
    // 删除回调
    handleRemove(file, fileList) {
      // 调用删除附件功能，将附件进行删除
      this.$modal.confirm('请确认是否删除附件名称为：'+file.name+' 的数据?').then(() => {
        let fjId = []
        let id = file.id || file.fj || file.response[0].fj
        fjId.push(id)
        delFj(fjId).then(res => {
          if (res.code === 200) {
            this.$message.success("删除成功！")
            this.fjList = fileList
          }
        })
      }).catch(() => {
        fileList.push(file)
      })
    },
    // 文件点击回调
    async handlePreview(file) {
      let id = file.id || file.fjid || file.fj || file.response[0].fj
      const response = await axios.get(this.uploadSrc + `/gd/fj/download/` + id, { responseType: 'blob', headers: this.uploadHeaders });
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url
      link.download = file.name;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    // 删除回调
    downFile(file) {
      // 调用删除附件功能，将附件进行删除
      getFjById(file.fjid, 'blob').then(response => {
        const binaryData = [];
        binaryData.push(response);
        let url = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/octet-stream' }));
        const link = document.createElement('a');
        link.href = url
        link.download = file.fjname;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      })
    },
    // ======  上传结束  ====
  }
}
</script>

<style scoped>

</style>
